<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>参数设置</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .section-card {
            background: white;
            border-radius: 0.75rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .input-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: #111827;
            margin-bottom: 0.5rem;
        }

        .preview-box {
            background: #f3f4f6;
            border-radius: 0.375rem;
            padding: 0.75rem;
            min-height: 3rem;
            white-space: pre-wrap;
        }

        .error {
            color: #ef4444;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }

        .match-result {
            font-size: 1.125rem;
            font-weight: 600;
            margin-top: 1rem;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
        }

        .match-yes {
            background: #dcfce7;
            color: #166534;
        }

        .match-no {
            background: #fee2e2;
            color: #b91c1c;
        }

        .log-box {
            background: #f3f4f6;
            border-radius: 0.375rem;
            padding: 0.75rem;
            min-height: 100px;
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen p-4">
    <div class="max-w-6xl mx-auto">
        <h1 class="text-2xl font-bold text-gray-900 mb-6">扫码参数设置</h1>
        <!-- 扫码内容输入区 -->
        <div class="section-card">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">扫码内容输入</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <p class="input-label">扫码1内容（客户零件号）：</p>
                    <input type="text" id="previewScan1"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring-blue-200"
                        value="B250425054823/X03-81120016/6/20250429//10/1811513813/3DB-S06423/20290429/ASN250425S01240"
                        oninput="updatePreviews()">
                </div>
                <div>
                    <p class="input-label">扫码2内容（厂内零件号）：</p>
                    <input type="text" id="previewScan2"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:border-blue-500 focus:ring-blue-200"
                        value="3DB$X03-81120016$B1001222$2504240001$6"
                        oninput="updatePreviews()">
                </div>
            </div>
        </div>
        <!-- 提取与比对规则区 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <!-- 提取规则设置 -->
            <div class="section-card">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">数据提取规则</h2>
                <div class="mb-6">
                    <p class="text-lg font-medium text-gray-700 mb-3">扫码1提取（客户零件号）</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <p class="input-label">起始位：</p>
                            <input type="number" id="scan1Start"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="1" min="1" oninput="updatePreviews()">
                        </div>
                        <div>
                            <p class="input-label">结束位：</p>
                            <input type="number" id="scan1End"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="10" min="1" oninput="updatePreviews()">
                        </div>
                    </div>
                    <p class="input-label mt-3">预览结果：</p>
                    <div id="scan1Preview" class="preview-box"></div>
                </div>
                <div>
                    <p class="text-lg font-medium text-gray-700 mb-3">扫码2提取（厂内零件号）</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <p class="input-label">起始位：</p>
                            <input type="number" id="scan2Start"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="1" min="1" oninput="updatePreviews()">
                        </div>
                        <div>
                            <p class="input-label">结束位：</p>
                            <input type="number" id="scan2End"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="10" min="1" oninput="updatePreviews()">
                        </div>
                    </div>
                    <p class="input-label mt-3">预览结果：</p>
                    <div id="scan2Preview" class="preview-box"></div>
                </div>
            </div>
            <!-- 比对规则设置 -->
            <div class="section-card">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">比对规则设置</h2>
                <div class="mb-6">
                    <p class="text-lg font-medium text-gray-700 mb-3">比对条件1（扫码1与扫码2指定位置匹配）</p>
                    <p class="text-sm text-gray-500 mb-3">格式：单数字（如5）或范围（如5-10）</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <p class="input-label">扫码1范围：</p>
                            <input type="text" id="compare1Scan1"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="如：5-16" oninput="validateRange('compare1Scan1')">
                            <div id="compare1Scan1Error" class="error"></div>
                        </div>
                        <div>
                            <p class="input-label">扫码2范围：</p>
                            <input type="text" id="compare1Scan2"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="如：15-26" oninput="validateRange('compare1Scan2')">
                            <div id="compare1Scan2Error" class="error"></div>
                        </div>
                    </div>
                    <p class="input-label mt-3">预览结果：</p>
                    <div class="space-y-2">
                        <div class="flex gap-2 items-center">
                            <span class="text-sm text-gray-600">扫码1提取值：</span>
                            <div id="compare1Preview1" class="preview-box flex-1"></div>
                        </div>
                        <div class="flex gap-2 items-center">
                            <span class="text-sm text-gray-600">扫码2提取值：</span>
                            <div id="compare1Preview2" class="preview-box flex-1"></div>
                        </div>
                        <div id="compare1Result" class="match-result"></div>
                    </div>
                </div>
                <div>
                    <p class="text-lg font-medium text-gray-700 mb-3">比对条件2（扫码1与扫码2指定位置匹配）</p>
                    <p class="text-sm text-gray-500 mb-3">格式：单数字（如8）或范围（如28-35）</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <p class="input-label">扫码1范围：</p>
                            <input type="text" id="compare2Scan1"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="如：38" oninput="validateRange('compare2Scan1')">
                            <div id="compare2Scan1Error" class="error"></div>
                        </div>
                        <div>
                            <p class="input-label">扫码2范围：</p>
                            <input type="text" id="compare2Scan2"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md"
                                placeholder="如：28" oninput="validateRange('compare2Scan2')">
                            <div id="compare2Scan2Error" class="error"></div>
                        </div>
                    </div>
                    <p class="input-label mt-3">预览结果：</p>
                    <div class="space-y-2">
                        <div class="flex gap-2 items-center">
                            <span class="text-sm text-gray-600">扫码1提取值：</span>
                            <div id="compare2Preview1" class="preview-box flex-1"></div>
                        </div>
                        <div class="flex gap-2 items-center">
                            <span class="text-sm text-gray-600">扫码2提取值：</span>
                            <div id="compare2Preview2" class="preview-box flex-1"></div>
                        </div>
                        <div id="compare2Result" class="match-result"></div>
                    </div>
                </div>
                <!-- 最终绑定状态 -->
                <div class="mt-6">
                    <p class="text-lg font-medium text-gray-700 mb-3">最终绑定状态</p>
                    <div id="finalBindResult" class="match-result"></div>
                </div>
            </div>
        </div>
        <button id="saveSettings"
            class="w-full bg-blue-600 text-white py-3 px-4 rounded-md hover:bg-blue-700 transition-colors mt-4">
            保存所有设置
        </button>
        <!-- 日志显示区 -->
        <div class="mt-4">
            <h2 class="text-lg font-medium text-gray-700 mb-2">操作日志</h2>
            <div id="logArea" class="log-box"></div>
        </div>
    </div>
    <script>
        // 记录日志
        function logMessage(message) {
            const logArea = document.getElementById('logArea');
            const logEntry = document.createElement('p');
            logEntry.textContent = `${new Date().toLocaleString()}: ${message}`;
            logArea.appendChild(logEntry);
            logArea.scrollTop = logArea.scrollHeight;
        }

        // 加载最后一次设置
        async function loadSettings() {
            try {
                logMessage('开始从服务器加载设置...');
                const response = await fetch('/settings');
                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }
                logMessage(`加载设置请求返回状态码: ${response.status}`);
                const settings = await response.json();
                document.getElementById('scan1Start').value = settings.extraction.scan1[0];
                document.getElementById('scan1End').value = settings.extraction.scan1[1];
                document.getElementById('scan2Start').value = settings.extraction.scan2[0];
                document.getElementById('scan2End').value = settings.extraction.scan2[1];
                document.getElementById('compare1Scan1').value = settings.compare.compare1.slice(0, 2).join('-');
                document.getElementById('compare1Scan2').value = settings.compare.compare1.slice(2, 4).join('-');
                document.getElementById('compare2Scan1').value = settings.compare.compare2.slice(0, 2).join('-');
                document.getElementById('compare2Scan2').value = settings.compare.compare2.slice(2, 4).join('-');
                updatePreviews();
                logMessage('设置加载成功');
            } catch (error) {
                logMessage(`加载设置失败: ${error.message}`);
                console.error("加载设置失败", error);
            }
        }

        // 实时更新所有预览内容及比对结果
        function updatePreviews() {
            logMessage('开始更新预览内容...');
            const scan1 = document.getElementById('previewScan1').value || "";
            const scan2 = document.getElementById('previewScan2').value || "";

            // 更新提取规则预览
            updateExtractionPreview('scan1', scan1);
            updateExtractionPreview('scan2', scan2);

            // 更新比对规则预览及匹配状态
            const condition1 = updateComparePreview('compare1', scan1, scan2);
            const condition2 = updateComparePreview('compare2', scan1, scan2);

            // 更新最终绑定状态（两个条件同时满足）
            const finalResultEl = document.getElementById('finalBindResult');
            if (condition1 && condition2) {
                finalResultEl.textContent = "✅ 双条件满足，允许绑定";
                finalResultEl.className = "match-result match-yes";
            } else {
                finalResultEl.textContent = "❌ 未同时满足双条件，禁止绑定";
                finalResultEl.className = "match-result match-no";
            }
            logMessage('预览内容更新完成');
        }

        // 更新比对规则预览并返回匹配状态
        function updateComparePreview(prefix, scan1, scan2) {
            const [s1Start, s1End] = parseRange(document.getElementById(`${prefix}Scan1`).value);
            const [s2Start, s2End] = parseRange(document.getElementById(`${prefix}Scan2`).value);
            const preview1El = document.getElementById(`${prefix}Preview1`);
            const preview2El = document.getElementById(`${prefix}Preview2`);
            const resultEl = document.getElementById(`${prefix}Result`);

            // 提取扫码值
            const value1 = s1Start? scan1.slice(s1Start - 1, s1End) || "" : "";
            const value2 = s2Start? scan2.slice(s2Start - 1, s2End) || "" : "";

            // 显示预览值
            preview1El.textContent = value1 || "无有效内容";
            preview2El.textContent = value2 || "无有效内容";

            // 判断是否匹配
            const isMatch = value1 === value2 && value1!== "" && value2!== "";
            resultEl.textContent = isMatch? "✅ 条件满足" : "❌ 条件不满足";
            resultEl.className = `match-result ${isMatch? 'match-yes' : 'match-no'}`;

            return isMatch;
        }

        // 更新提取规则预览（通用函数）
        function updateExtractionPreview(scanType, scanText) {
            const start = Math.max(1, parseInt(document.getElementById(`${scanType}Start`).value) || 1);
            const end = Math.max(start, parseInt(document.getElementById(`${scanType}End`).value) || start);
            const previewEl = document.getElementById(`${scanType}Preview`);
            const extracted = scanText.slice(start - 1, end);
            previewEl.textContent = extracted || "无有效内容（范围超出扫码长度）";
        }

        // 验证比对范围输入（支持单数字和范围）
        function validateRange(inputId) {
            const input = document.getElementById(inputId);
            const errorEl = document.getElementById(`${inputId}Error`);
            const value = input.value.trim();
            const regex = /^\d+(-\d+)?$/;

            if (!value) {
                errorEl.textContent = "";
                return true;
            }
            if (!regex.test(value)) {
                errorEl.textContent = "格式错误，示例：5 或 5-10";
                return false;
            }

            const [start, end] = parseRange(value);
            if (start < 1) {
                errorEl.textContent = "位置必须大于0";
                return false;
            }
            if (end < start) {
                errorEl.textContent = "结束位不能小于起始位";
                return false;
            }

            errorEl.textContent = "";
            return true;
        }

        // 解析输入范围（单数字转[num, num]，范围转[start, end]）
        function parseRange(input) {
            if (!input) return [null, null];
            const parts = input.split('-').map(Number);
            return parts.length === 1? [parts[0], parts[0]] : [parts[0], parts[1]];
        }

        // 保存设置
        document.getElementById('saveSettings').addEventListener('click', async () => {
            logMessage('开始保存设置...');
            const validations = [
                validateRange('compare1Scan1'),
                validateRange('compare1Scan2'),
                validateRange('compare2Scan1'),
                validateRange('compare2Scan2')
            ];

            if (!validations.every(valid => valid)) {
                logMessage('比对范围格式有误，请检查输入');
                alert("比对范围格式有误，请检查输入");
                return;
            }

            const settings = {
                extraction: {
                    scan1: [parseInt(document.getElementById('scan1Start').value), parseInt(document.getElementById('scan1End').value)],
                    scan2: [parseInt(document.getElementById('scan2Start').value), parseInt(document.getElementById('scan2End').value)]
                },
                compare: {
                    compare1: [...parseRange(document.getElementById('compare1Scan1').value), ...parseRange(document.getElementById('compare1Scan2').value)],
                    compare2: [...parseRange(document.getElementById('compare2Scan1').value), ...parseRange(document.getElementById('compare2Scan2').value)]
                }
            };

            try {
                const response = await fetch('/settings', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(settings)
                });
                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }
                logMessage(`保存设置请求返回状态码: ${response.status}`);
                logMessage('设置保存成功');
                alert("设置保存成功！\n提示：绑定需同时满足两个比对条件");
            } catch (error) {
                logMessage(`保存设置失败: ${error.message}`);
                alert(`保存设置失败: ${error.message}`);
            }
        });

        // 页面加载时加载设置
        window.addEventListener('load', loadSettings);
    </script>
</body>

</html>    